<template>
  <div v-if="film">
    <img class="poster" :src="film.poster" alt="" />

    <div class="info">
      <p class="first">{{ film.name }}<span class="grade">{{ film.grade }}</span></p>
      <p>{{ film.category }}</p>
      <p><span>{{ film.nation }}</span>&nbsp;|&nbsp;<span>{{ film.runtime }}分钟</span></p>
      <p class="synopsis">{{ film.synopsis }}</p>

    </div>

    <div>
      <p>猜你喜欢</p>

      <p class="aifan">
        <RouterLink to="/film/6165">阿凡达：水之道</RouterLink>
      </p>
    </div>

  </div>
  <van-button type="primary" block color="#faaf00" square>选座购票</van-button>
</template>

<script>
export default {
  name: "Film",

  data() {
    return {
      // 用于存放电影详情数据
      film: null,
      newFilmId: this.$route.params.id,
    };
  },

  beforeRouteUpdate(to, from, next) {
    // console.log("beforeRouteUpdate");
    // console.log("to", to);
    // console.log("from", from);
    // 如果不调用 next() 的话，相当于就阻止了导航（跳转）
    next();

    // 放行之后，调用 this.fetchData() 重新获取数据
    // 问题： fetchData 里面获取 this.$route.params.id 的数据还是上一次的数据
    // 解决方案：从to这个参数上获取到想要的数据，然后传递给 fetchData。相应的 fetchData 也需要改造一番
    const newFilmId = to.params.id;
    console.log("newFilmId", newFilmId);
    this.fetchData(newFilmId);
  },

  mounted() {
    console.log("mounted", this.newFilmId);
    this.fetchData(this.newFilmId);
  },

  methods: {
    async fetchData(id) {
      // 获取 filmId 通过 $route.params.id
      //             如果有传递id就使用传递过来的id，否则通过 $route.params.id 获取
      const filmId = id || this.$route.params.id;
      // 请求地址
      const url = `https://m.maizuo.com/gateway?filmId=${filmId}`;

      const result = await fetch(url, {
        headers: {
          "X-Host": "mall.film-ticket.film.info",
        },
      }).then((response) => response.json());

      // 判断 业务编码 status 是否为0
      if (result.status === 0) {
        this.film = result.data.film;
      } else {
        alert(result.msg);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.poster {
  display: block;
  width: 100%;
  height: 294px;
  overflow: hidden;
}

.info {
  font-size: 14px;
  padding: 10px;
  box-sizing: border-box;

  .first {
    display: flex;
    justify-content: space-between;
    font-size: 20px;
    font-weight: bold;
  }

  .grade {
    font-weight: 700;
    color: #faaf00;
    font-size: 18px;
  }
}

.synopsis {
  font-size: 14px;
  line-height: 24px;
  margin: 20px 0;
  display: -webkit-box;

  overflow: hidden;

  white-space: normal !important;

  text-overflow: ellipsis;

  word-wrap: break-word;

  -webkit-line-clamp: 3;

  -webkit-box-orient: vertical
}

.aifan {
  margin-bottom: 70px;
}
</style>
